bubblesort python

29

def bubble_sort(li_to_sort):
    # Looping from size of array from last index[-1] to index [0]
    for n in range(len(li_to_sort)-1, 0, -1):
        for i in range(n):
            if li_to_sort[i] > li_to_sort[i + 1]:
                # swapping data if the element is less than next element in the array
                li_to_sort[i], li_to_sort[i + 1] = li_to_sort[i + 1], li_to_sort[i]


li = [39, 12, 18, 85, 72, 10, 2, 18]

print("Unsorted list: ", li)
bubble_sort(li)
print("Sorted List: ", li)
"""Bubblesort
"""
## Un-optimised--------------------------------------------------------------
def bubble_1(lst):
    n = len(lst) - 1
    for i in range(n):
        # Within the unsorted portion
        for j in range(n - i):
            # If curr > next, swap
            if lst[j] > lst[j+1]:
                lst[j], lst[j+1] = lst[j+1], lst[j]
    return lst # for easy testing

def bubble_2(lst):
    n = len(lst) - 1
    # Within the unsorted portion, except the last number
    for unsorted in range(n, 0, -1):
        for i in range(unsorted):
            # If curr > next, swap
            if lst[i] > lst[i+1]:
                lst[i], lst[i+1] = lst[i+1], lst[i]
    return lst # for easy testing

## Optimised-----------------------------------------------------------------
def bubble_3(lst):
    n = len(lst) - 1
    
    # Within the unsorted portion, except the last number
    for unsorted in range(n, 0, -1):
        swapped = False
        for i in range(unsorted):
            # If curr > next, swap
            if lst[i] > lst[i+1]:
                lst[i], lst[i+1] = lst[i+1], lst[i]
                swapped = True
        
        # Check if its sorted by this time
        if not swapped:
            break
    return lst # for easy testing

Comments

Submit
0 Comments